<template>
  <el-form ref="formRef" :model="form" :rules="rules" :show-message="false" label-width="100px" size="default" label-suffix="：">
    <el-row>
      <el-col :span="24">
        <el-form-item label="字典名称" prop="demo1">
          <el-input v-model="form.demo1" placeholder="请输入字典名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="字典类型" prop="demo1">
          <el-input v-model="form.demo1" placeholder="请输入字典类型"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="状态">
          <el-radio-group v-model="form.demo3">
            <el-radio label="1">正常</el-radio>
            <el-radio label="-1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="备注">
          <el-input
              v-model="form.demo1"
              :rows="3"
              type="textarea"
              placeholder="请输入备注"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup name="x-form">
import useStore from '@/stores/modules/sys/dict';
const sysDict = useStore();
const formRef = ref()

import {reactive, ref} from "vue";

const form = reactive({
  demo1: "",
  demo2: "",
  demo3: "1"
})

const rules = ref({
  demo1: { required: true, message: '不能为空', trigger: 'click'},
  demo2: { required: true, message: '不能为空', trigger: 'click'},
})

/**
 * 表单验证
 * @param callback
 * @returns {Promise<void>}
 */
const doValidate = async (callback) => {
  await formRef.value.validate((valid, fields) => {
    if (! valid) {
      let errMsg = Helper.getFirstMessage(fields);
      if (errMsg) {
        Msg.error(errMsg)
      }
      callback(false)
      return
    }

    callback(form)
  })
}

/**
 * 保存
 * @returns {Promise<void>}
 */
const submit = async () => {
  await doValidate(async (form) => {
    if (form == false) {
      return
    }
  })
}

/**
 * 获取数据
 * @param data
 */
const render = (data) => {
  if (! Helper.empty(data)) {
    for (let key in data) {
      form[key] = data[key]
    }
  }
}

defineExpose({ render, submit })
</script>